use loco_rs::prelude::*;
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

pub use super::_entities::order_returns::{self, ActiveModel, Entity, Model};

#[derive(Debug, Deserialize, Serialize)]
pub struct CreateParams {
    pub order_id: String,
    pub order_item_id: String,
    pub reason: String,
    pub quantity: i32,
    pub amount: Decimal,
    pub status: String,
    pub comment: Option<String>,
}

#[derive(Debug, Validate, Deserialize)]
pub struct Validator {
    #[validate(length(min = 1, message = "Order ID must not be empty."))]
    pub order_id: String,
    #[validate(length(min = 1, message = "Order Item ID must not be empty."))]
    pub order_item_id: String,
    #[validate(length(min = 1, message = "Comment must not be empty."))]
    pub comment: String,
    #[validate(length(min = 1, message = "Status must not be empty."))]
    pub status: String,
}

impl Validatable for ActiveModel {
    fn validator(&self) -> Box<dyn Validate> {
        Box::new(Validator {
            order_id: self.order_id.as_ref().to_owned(),
            order_item_id: self.order_item_id.as_ref().to_owned(),
            comment: self.comment.as_ref().to_owned(),
            status: self.status.as_ref().to_owned(),
        })
    }
}

#[async_trait::async_trait]
impl ActiveModelBehavior for ActiveModel {
    async fn before_save<C>(self, _db: &C, insert: bool) -> Result<Self, DbErr>
    where
        C: ConnectionTrait,
    {
        self.validate()?;
        if insert {
            let mut this = self;
            this.id = ActiveValue::Set(Uuid::new_v4().to_string());
            Ok(this)
        } else {
            Ok(self)
        }
    }
}

impl Model {
    /// finds an order return by the provided id
    ///
    /// # Errors
    ///
    /// When could not find order return or DB query error
    pub async fn find_by_id(db: &DatabaseConnection, id: &str) -> ModelResult<Self> {
        let order_return = order_returns::Entity::find()
            .filter(
                model::query::condition()
                    .eq(order_returns::Column::Id, id)
                    .build(),
            )
            .one(db)
            .await?;
        order_return.ok_or_else(|| ModelError::EntityNotFound)
    }

    /// finds order returns by the provided order id
    ///
    /// # Errors
    ///
    /// When could not find order returns or DB query error
    pub async fn find_by_order_id(
        db: &DatabaseConnection,
        order_id: &str,
    ) -> ModelResult<Vec<Self>> {
        let order_returns = order_returns::Entity::find()
            .filter(
                model::query::condition()
                    .eq(order_returns::Column::OrderId, order_id)
                    .build(),
            )
            .all(db)
            .await?;
        Ok(order_returns)
    }

    /// finds order returns by the provided order item id
    ///
    /// # Errors
    ///
    /// When could not find order returns or DB query error
    pub async fn find_by_order_item_id(
        db: &DatabaseConnection,
        order_item_id: &str,
    ) -> ModelResult<Vec<Self>> {
        let order_returns = order_returns::Entity::find()
            .filter(
                model::query::condition()
                    .eq(order_returns::Column::OrderItemId, order_item_id)
                    .build(),
            )
            .all(db)
            .await?;
        Ok(order_returns)
    }

    /// finds order returns by the provided status
    ///
    /// # Errors
    ///
    /// When could not find order returns or DB query error
    pub async fn find_by_status(db: &DatabaseConnection, status: &str) -> ModelResult<Vec<Self>> {
        let order_returns = order_returns::Entity::find()
            .filter(
                model::query::condition()
                    .eq(order_returns::Column::Status, status)
                    .build(),
            )
            .all(db)
            .await?;
        Ok(order_returns)
    }

    /// Asynchronously creates an order return and saves it to the database.
    ///
    /// # Errors
    ///
    /// When could not save the order return into the DB
    pub async fn create(db: &DatabaseConnection, params: &CreateParams) -> ModelResult<Self> {
        let order_return = order_returns::ActiveModel {
            order_id: ActiveValue::set(params.order_id.to_string()),
            order_item_id: ActiveValue::set(params.order_item_id.to_string()),
            quantity: ActiveValue::set(params.quantity),
            status: ActiveValue::set(params.status.to_string()),
            comment: ActiveValue::set(params.comment.clone().unwrap_or_default()),
            ..Default::default()
        }
        .insert(db)
        .await?;

        Ok(order_return)
    }
}

impl ActiveModel {
    /// Updates the order return's status
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_status(
        mut self,
        db: &DatabaseConnection,
        status: String,
    ) -> ModelResult<Model> {
        self.status = ActiveValue::set(status);
        Ok(self.update(db).await?)
    }

    /// Updates the order return's comment
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_comment(
        mut self,
        db: &DatabaseConnection,
        comment: Option<String>,
    ) -> ModelResult<Model> {
        self.comment = ActiveValue::set(comment.unwrap_or_default());
        Ok(self.update(db).await?)
    }

    pub async fn update_quantity(
        mut self,
        db: &DatabaseConnection,
        quantity: i32,
    ) -> ModelResult<Model> {
        self.quantity = ActiveValue::set(quantity);
        Ok(self.update(db).await?)
    }
}
